import {
	api
} from './api.js'
let avatar = '/static/common/avatar.png'

class common {
	apiHost = 'http://ctxpt.ynxbgg.com/'
	// uploadPath = '/api/services/app/configuration/Upload'
	uploadPath = 'QiNiu/UploadImgToQiNiu'
	appName = "骋泰鑫拼团";
	
	companyName = "骋泰鑫拼团"; // 公司名称

	servicePhone = '0871-64895913'
	
	pageSize = 10;
	appVersion = 'v1.0.0'
	/** 手机号验证正则 */
	phoneReg = /^0?(13|14|15|18|17)[\d]{9}$/;
	/** 不能以空格开头 */
	spaceReg = /^[^\s]+/;
	/** 不能有中文字符 */
	zhCNReg = /^[\x00-\xff]*$/;
	/** 数字正则 */
	numberReg = /^[0-9]*$/;
	// 字母正则
	letterReg = /[a-zA-Z]/;
	/** 身份证号 */
	IDCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	// 银行卡号
	CardReg = /^([1-9]{1})(\d{15}|\d{18})$/;

	userSexArr = ['男', '女', '保密']; // 1 = Man , 2 = Women , 3 = UnKnow

	banks = ['中国人民银行', '国家开发银行', '中国进出口银行', '中国农业发展银行', '中国工商银行', '中国农业银行', '中国银行', '中国建设银行', '交通银行', '中国邮政储蓄银行',
		'中国光大银行', '中国民生银行', '招商银行', '华夏银行', '中信银行', '上海浦东发展银行', '平安银行', '广发银行', '兴业银行', '浙商银行', '渤海银行', '恒丰银行'
	]

	defaultId = '00000000-0000-0000-0000-000000000000'

	bean = '积分'
	
	// 文章详情code,  抽奖玩法介绍：ptwfjs，如何发起拼团：rhfqpt，公司简介：gsjj，隐私政策：yszc，服务协议：fwxy， 特权权益说明： tqqysm, 商家入驻协议： sjrzxy
	artCode = { ptwfjs: 'ptwfjs', rhfqpt: 'rhfqpt', gsjj: 'gsjj', yszc: 'yszc', fwxy: 'fwxy', tqqysm: 'tqqysm', sjrzxy: 'sjrzxy' }

	needLogin = [{
			url: '/pages/mine/order',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/address',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/orderTeam',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/orderTeamDetail',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/orderConfirm',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/orderTeamConfirm',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/cartConfirm',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/orderPay',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/orderDetail',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/bank',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/bean',
			isAuth: true,
			isBindPhone: false
		},
		{
			url: '/pages/mine/coupon',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/team',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/mine/auth',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/share/share',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/shop/coupon',
			isAuth: true,
			isBindPhone: false
		},
		{
			url: '/pages/shop/shopIn',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/shop/shopAuth',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/shop/shopInPay',
			isAuth: true,
			isBindPhone: true
		},
		{
			url: '/pages/cart/cart',
			isAuth: true,
			isBindPhone: true
		}
	]

	gradeType = [{
			id: 0,
			title: '全部'
		},
		{
			id: 1,
			title: '一级成员'
		},
		{
			id: 2,
			title: '二级成员'
		}
	]

	grade = [{
			id: 1,
			title: '团长/店长'
		},
		{
			id: 2,
			title: '普通会员'
		}
	]

	/* orderArr =  [
			{ id: -2, title: '购物退款' },
			{ id: -1, title: '拼团退款' },
			{ id: '', title: '全部' },
			{ id: 0, title: '待付款'},
			{ id: 2, title: '待发货' },
			{ id: 3, title: '待收货' },
			{ id: 4, title: '申请退款' },
			{ id: 5, title: '已完成' },
	] */

	orderArr = [{
			id: 'all',
			title: '全部'
		},
		{
			id: 0,
			title: '待付款'
		},
		{
			id: 2,
			title: '待发货'
		},
		{
			id: 3,
			title: '待收货'
		},
		{
			id: 5,
			title: '已完成'
		}
	]

	orderTypeArr = [{
			id: 1,
			title: '升级团长'
		},
		{
			id: 2,
			title: '拼团'
		},
		{
			id: 3,
			title: '购物'
		},
		{
			id: 4,
			title: '钱包充值'
		}
	]
	
	htmlToText = (html) =>
	{
	  var input = html || '';
	  // return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');
	  return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');
	}

	/* 字符串截取方法 */
	stringPartOf = (str, length) => {
		if (!str) return str
		let len = str.length
		if (len <= length) return str
		return str.substr(0, length) + '...'
	}

	phonePartOf = (phone) => {
		phone = phone || ''
		phone = phone.toString()
		if (!phone || phone.length < 11) return phone;
		return phone.substr(0, 3) + '****' + phone.substr(-4)
	}

	namePartOf = (name) => {
		if (!name) return name;
		let len = name.length
		if (len < 2) return name
		else if (len === 2) {
			return name.substr(0, 1) + '*'
		} else {
			return name.substr(0, 1) + '*'.repeat(len - 2) + name.substr(-1)
		}
	}

	cardNumPartOf = (value) => {
		var cardNum = value || "";
		return "*** **** **** **** " + cardNum.substr(-4);
	}

	// 小于0的数字加0补全
	formatNumber = (value) => {
		if (typeof value !== 'number') return value
		if (value >= 1 && value < 10) {
			return '0' + value
		}
		return value
	}

	// money四舍五入
	formatMoney = (value) => {
		if (typeof value !== 'number') return value
		return value.toFixed(1)
	}

	// 后台返回的时间截
	subTime = (time) => {
		time = time ? time : ''
		let pos = time.indexOf('T')
		if (pos !== -1) {
			let temp = time.replace('T', ' ')
			return temp.substr(0, 19)
		}
		return time
	}

	getAvatar(src) {
		return src || avatar
	}

	setUserInfo = (info) => {
		uni.setStorageSync("user", info ? JSON.stringify(info) : "");
	}

	// 获取用户信息
	getUserInfo = () => {
		var data = uni.getStorageSync("user") || {};
		return Object.keys(data).length > 0 ? JSON.parse(data) : ''
	}

	// 更新用户信息
	updateUserInfo = (field, value) => {
		var data = JSON.parse(uni.getStorageSync("user")) || {};
		data[field] = value
		this.setUserInfo(data)
	}

	getToken = () => {
		const user = this.getUserInfo() || {};
		if (Object.keys(user).length <= 0) return {
			Authorization: ""
		}
		return {
			Authorization: "Bearer " + user.token
		};
		// return { Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzNjVERTAyRkIzNkQ3MTY5RUY1QzA2QTA5RDg5QkMxNTJBRTZENTE4QjU0NDA2RjYyQTA0MTc4NkNFRTlEODE0Q0Y3MTUyNENCQkZEMjBCNSIsImlhdCI6IjE1ODcxNzg2NTYiLCJuYmYiOiIxNTg3MTc4NjU2IiwiZXhwIjoiMTU4Nzc4MzQ1NiIsImlzcyI6IkFQSSIsImF1ZCI6IlVzZXIiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4ifQ.Bi9iSBGqU-MYfLLVaHYKr0gVxX-0FG9r6ALntXY27S0"}
	}

	/**
	 * @param isBindPhone: '是否判断已经绑定手机号'
	 */
	isLogin = () => {
		let userInfo = this.getUserInfo()
		return userInfo.token ? userInfo.token : false
	}

	isBindPhone = () => {
		let userInfo = this.getUserInfo()
		return userInfo.userPhone ? userInfo.userPhone : false
	}

	setStorage = (key, value) => {
		uni.setStorageSync(key, value ? JSON.stringify(value) : "");
	}

	getStorage = (key) => {
		var data = uni.getStorageSync(key);
		return data ? JSON.parse(data) : null
	}

	/* 表单检查函数 */
	isNumber = (str) => {
		let reg = new RegExp(this.numberReg)
		return reg.test(str)
	}

	isLetter = (str) => {
		return new RegExp(this.letterReg).test(str)
	}

	isPhone = (str) => {
		let reg = new RegExp(this.phoneReg)
		// return reg.test(str)
		return true
	}

	isIDCard = (str) => {
		let reg = new RegExp(this.IDCardReg)
		return reg.test(str)
	}

	isBankCard = (str) => {
		let reg = new RegExp(this.CardReg)
		return reg.test(str)
	}

	// 路由跳转
	navigateTo = (url) => {
		let needLogin = this.needLogin
		let temp = url
		let pos = url.indexOf('?')
		if (pos !== -1) {
			temp = url.substring(0, pos)
		}
		let flag = true
		needLogin.map(item => {
			if (temp === item.url) {
				if (!this.isLogin()) {
					this.getWechatCode()
					flag = false
				} else {
					if (!this.isBindPhone()) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
						flag = false
					}
				}
			}
		})
		
		if (flag) {
			if (url === '/' || url === '/pages/index/index' || url === 'pages/message/message' || url === '/pages/cart/cart' || url ===
				'/pages/mine/mine') {
				uni.switchTab({
					url
				})
			} else {
				uni.navigateTo({
					url
				})
			}
		}
	}

	showToast = (title, duration) => {
		uni.showToast({
			title: title || '标题',
			duration: duration || 2000,
			icon: 'none'
		})
	}

	showModal = (title, content, callback) => {
		uni.showModal({
			title: title || '温馨提示',
			content: content || '确定要进行此操作吗?',
			success: function(res) {
				if (res.confirm) {
					callback && callback()
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	// 图片上传
	imgUpload = (callBack) => {
		uni.chooseImage({
			sourceType: ['album', 'camera'],
			count: 1,
			sizeType: ['compressed'], // 图片尺寸，选项原图和压缩， h5端未实现压缩
		}).then(res => {
			console.log(res)
			let tempFiles = res[1].tempFiles[0]
			uni.showLoading({
				title: '图片上传中...'
			})
			uni.uploadFile({
				url: this.apiHost + this.uploadPath,
				filePath: tempFiles.path,
				name: 'file',
				header: this.getToken()
			}).then(imgRes => {
				uni.hideLoading()
				imgRes = imgRes[1]
				// console.log(imgRes)
				if (imgRes.statusCode != 200) {
					this.showToast('上传图片失败,错误原因: ' + imgRes.errMsg);
					return
				}
				// 图片正确上传
				let imgPath = JSON.parse(imgRes.data).result
				callBack && callBack(imgPath)
			}).catch(err1 => {
				uni.hideLoading()
				this.showToast('上传图片失败,请稍后重试~')
			})
		}).catch(err => {
			console.error(err)
			this.showToast('打开图片失败,请稍后重试~')
		})
	}

	makePhoneCall = (phoneNumber) => {
		uni.makePhoneCall({
			phoneNumber: phoneNumber || this.servicePhone,
		})
	}

	getWechatCode = () => {
		let url = this.apiHost + '/wechat/GetWechatCode'
		window.location.href = url
	}
	
	updataUserInfo = () => {
		if(this.isLogin()) {
			api.getUserInfoAsync({}, (res) => {
				let token = this.getUserInfo().token
				res.token = token
				this.setUserInfo(res)
			})
		}
	}

	uniPay(payParams, orderInfo, callBack) {
		// #ifdef  H5
		this.wxH5Pay(payParams, callBack)
		// #endif

		// #ifndef H5 
		this.appPay(payParams, orderInfo, callBack)
		// #endif 
	}

	/**
	 *  h5微信支付
	 */
	wxH5Pay = (payParams, callback) => {
		if (typeof window['WeixinJSBridge'] == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady',
					() => this.onBridgeReady(payParams, callback), false);
			} else if (document['attachEvent']) {
				document['attachEvent']('WeixinJSBridgeReady',
					() => this.onBridgeReady(payParams, callback));
				document['attachEvent']('onWeixinJSBridgeReady',
					() => this.onBridgeReady(payParams, callback));
			}
		} else {
			this.onBridgeReady(payParams, callback);
		}
	}


	onBridgeReady = (payParams, callback) => {
		const that = this;
		window['WeixinJSBridge'].invoke(
			'getBrandWCPayRequest',
			payParams,
			function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					callback();
				} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
					that.showToast("支付取消");
				} else if (res.err_msg == "get_brand_wcpay_request:fail") {
					that.showToast('支付失败');
				}
			}
		);
	}

	appPay(payParams, orderInfo, callback) {
		uni.requestPayment({
			provider: 'weixin',
			orderInfo: JSON.stringify(orderInfo), // app中是字符串类型
			timeStamp: payParams.timeStamp,
			nonceStr: timeStamp.nonceStr,
			package: timeStamp.package,
			signType: timeStamp.signType,
			paySign: timeStamp.paySign,
			success() {
				callback()
			},
			fail() {
				that.showToast('调起支付失败, 请稍后重试~')
			}
		})
	}
	
	uniShare(href, title, summary, imageUrl) {
		let that = this
		uni.share({
		    provider: "weixin",
		    scene: "WXSceneSession",
		    type: 0,
		    href,
		    title,
		    summary,
		    imageUrl,
		    success: function (res) {
		        that.showToast('分享成功~')
		    },
		    fail: function (err) {
		         that.showToast('分享错误，请稍后重试~')
		    }
		})
	}
	
	uniShareLine(href, title, summary, imageUrl) {
		let that = this
		uni.share({
		    provider: "weixin",
		    scene: "WXSenceTimeline",
		    type: 0,
		    href,
		    title,
		    summary,
		    imageUrl,
		    success: function (res) {
		        that.showToast('分享成功~')
		    },
		    fail: function (err) {
		         that.showToast('分享出现错误，请稍后重试~')
		    }
		});
	}
}

export default new common
